package com.aiolos.weather.util;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;

/**
 * 将xml文件转换为Java对象的工具类
 */
public class XmlBuilder {

    /**
     * 将xml字符串转换为指定的POJO对象
     * @param clazz
     * @param xmlStr
     * @return
     * @throws Exception
     */
    public static Object xmlStrToObj(Class<?> clazz, String xmlStr) throws Exception{
        Object xmlObjext = null;
        JAXBContext context = JAXBContext.newInstance(clazz);
        //将xml字符串解析为POJO对象
        Unmarshaller unmarshaller = context.createUnmarshaller();
        Reader reader = new StringReader(xmlStr);

        try {
            xmlObjext = unmarshaller.unmarshal(reader);
        } catch (JAXBException e) {
            e.printStackTrace();
        } finally {
            if(null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return xmlObjext;
    }
}
